<template>
  <div class="login-container">
    <div class="back-card">
      <div class="login-card" ref="loginCardRef">
        <el-form ref="loginFormRef" :rules="rules" :model="form" label-width="0" size="large" hide-required-asterisk>
          <div class="login-title">Ban Cloud</div>
          <TransitionGroup name="list">
            <el-form-item prop="email" key="email">
              <el-input v-model="form.email" placeholder="请输入邮箱">
              </el-input>
            </el-form-item>

            <el-form-item v-if="
              loginBy === LOGIN_BY.CODE || signStatus === SIGN_STATUS.REGISTER
            " prop="code" key="code">
              <div class="code-input-container">
                <el-input v-model="form.code" placeholder="请输入验证码">
                </el-input>
                <el-button :disabled="countdown > 0" type="primary" @click="sendCode" class="send-code-btn">
                  {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item v-if="
              loginBy === LOGIN_BY.PASSWORD ||
              signStatus === SIGN_STATUS.REGISTER
            " prop="password" key="password">
              <el-input v-model="form.password" placeholder="请输入密码" show-password>
              </el-input>
            </el-form-item>

            <el-form-item v-if="signStatus === SIGN_STATUS.REGISTER" prop="nickname" key="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称">
              </el-input>
            </el-form-item>

            <div v-if="signStatus === SIGN_STATUS.LOGIN" class="tip-text" @click="changeLoginBy" key="tip">
              <p>
                {{ loginBy === LOGIN_BY.PASSWORD ? '验证码登录' : '密码登录' }}
              </p>
              <el-icon>
                <Sort />
              </el-icon>
            </div>

            <el-form-item key="submit">
              <el-button class="submit-button" type="primary" round @click="handleSubmit(signStatus)">{{
                signStatus === SIGN_STATUS.REGISTER ? '注册' : '登录'
              }}</el-button>
            </el-form-item>
          </TransitionGroup>
        </el-form>
      </div>

      <!-- 切换 -->
      <div class="to-login">
        <img src="../../assets/login.png" />
        <el-button type="primary" round plain @click="changeStatus(SIGN_STATUS.LOGIN)">
          登录
        </el-button>
      </div>
      <div class="to-register">
        <img src="../../assets/dog.png" />
        <el-button type="primary" round plain @click="changeStatus(SIGN_STATUS.REGISTER)">注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { validateEmail, validatePassword } from '@/utils'
import { SIGN_STATUS, LOGIN_BY } from './constants'
import { PlainMessage } from '@/utils'
import service from '@/utils/api'
import { URLS } from '@/constants'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const signStatus = ref(SIGN_STATUS.LOGIN)
const loginBy = ref(LOGIN_BY.PASSWORD)

const loginCardRef = ref(null)
const loginFormRef = ref(null)

const countdown = ref(0)
let timer = null

const form = ref({
  email: '',
  password: '',
  nickname: '',
  code: ''
})

const rules = ref({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '请输入6位验证码', trigger: 'blur' }
  ]
})

const sendCode = () => {
  loginFormRef.value.validateField('email', valid => {
    if (valid) {
      service.post(signStatus.value === SIGN_STATUS.LOGIN ? URLS.GET_LOGIN_CODE : URLS.GET_REGISTER_CODE, {
        email: form.value.email
      }).then(() => {
        startCountdown()
        PlainMessage.success('验证码已发送至您的邮箱')
      }).catch(() => {
        countdown.value = 0
      })
    } else {
      PlainMessage.error('请输入正确的邮箱')
    }
  })
}

const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    --countdown.value <= 0 && clearInterval(timer)
  }, 1000)
}

const handleLoginSuccess = (res) => {
  const { token, userInfo } = res.data
  localStorage.setItem('token', token)
  userStore.setUserInfo(userInfo)
  PlainMessage.success('登录成功')
  router.push('/main/all')
}

const handleSubmit = status => {
  loginFormRef.value.validate(valid => {
    if (valid) {
      if (status === SIGN_STATUS.LOGIN) {
        service.post(URLS.LOGIN, {
          type: loginBy.value,
          email: form.value.email,
          password: form.value.password,
          code: form.value.code
        }).then((res) => {
          handleLoginSuccess(res)
        })
      } else if (status === SIGN_STATUS.REGISTER) {
        service.post(URLS.REGISTER, {
          email: form.value.email,
          code: form.value.code,
          password: form.value.password,
          nickname: form.value.nickname
        }).then(() => {
          PlainMessage.success('注册成功')
          changeStatus(SIGN_STATUS.LOGIN)
        })
      }
    } else {
      PlainMessage.error('请填写正确信息')
      return false
    }
  })
}

const changeStatus = status => {
  signStatus.value = status
  if (status === SIGN_STATUS.LOGIN) {
    loginCardRef.value.style.transform = 'translateX(0)'
    loginCardRef.value.style.height = '420px'
    loginCardRef.value.style.top = '-20px'
  } else if (status === SIGN_STATUS.REGISTER) {
    loginCardRef.value.style.transform = 'translateX(342px)'
    loginCardRef.value.style.height = '470px'
    loginCardRef.value.style.top = '-40px'
  }
}

const changeLoginBy = () => {
  loginBy.value =
    loginBy.value === LOGIN_BY.PASSWORD ? LOGIN_BY.CODE : LOGIN_BY.PASSWORD
}

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})

</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;

  .back-card {
    display: flex;
    justify-content: space-evenly;
    position: relative;
    width: 780px;
    height: 380px;
    border-radius: 5px;
    border: 1px solid #a4b4c7;
    box-shadow: 0 0 5px #a4b4c7;

    .login-card {
      position: absolute;
      top: -20px;
      left: 5%;
      padding: 0 50px;
      width: 360px;
      height: 420px;
      background-color: #fff;
      border-radius: inherit;
      border: 1px solid #a4b4c7;
      box-shadow: 0 0 5px #a4b4c7;
      transition: all 0.5s;
      z-index: 1;

      .login-title {
        margin: 15% 0;
        text-align: center;
        font-size: 36px;
        font-weight: 700;
        color: var(--el-color-primary);
      }

      .submit-button {
        margin-top: 5%;
        width: 100%;
      }

      .tip-text {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: var(--el-color-primary);
        cursor: pointer;
      }

      .code-input-container {
        display: flex;
        gap: 10px;

        .send-code-btn {
          white-space: nowrap;
          flex-shrink: 0;
        }

        .el-input {
          flex-grow: 1;
        }
      }
    }

    .to-register,
    .to-login {
      display: flex;
      flex-direction: column;
      width: 300px;

      img {
        width: 100%;
      }
    }

    .to-register {
      transform: translate(20px, 40px);

      img {
        margin-bottom: 54px;
      }
    }
  }

}

.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.list-leave-active {
  position: absolute;
  display: none;
}
</style>
